use axum::{
    response::{IntoResponse, Redirect},
    Form,
};
use tower_cookies::{
    cookie::time::{Duration, OffsetDateTime},
    Cookie, Cookies,
};
use uuid::Uuid;

use crate::{service::setting_service, ApiResponse, CommParam, TOKEN_NAME};

pub async fn login(cookies: Cookies, param: Form<CommParam>) -> ApiResponse<String> {
    let param = param.0;
    let setting = setting_service::get().await;
    if param.pwd == setting.webpass {
        let mut cookie = Cookie::new(TOKEN_NAME, Uuid::new_v4().to_string());
        let mut now = OffsetDateTime::now_utc();
        now += Duration::hours(2);
        cookie.set_expires(now);
        cookies.add(cookie);
        let to_url = param.redirect.map_or("/index".to_string(), |f| f);
        return ApiResponse::from(to_url);
    }
    ApiResponse::from_error("密码错误")
}

pub async fn logout(cookies: Cookies) -> impl IntoResponse {
    cookies.remove(Cookie::new(TOKEN_NAME, ""));
    Redirect::to("/index")
}
